<?php
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;
use think\facade\Cache;
use think\facade\Db;

class Login extends BaseController
{

    /**
     * @return object
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 微信注册
     * TODO 暂未做完
     */
    public function login()
    {
        $examinee_number = $this->request->post('examinee_number');
        $password = $this->request->post('password');
        $captcha = $this->request->post('captcha');
        $captchaKey = $this->request->post('key');
        $cacheCaptcha = Cache::get($captchaKey);
//        if (strtoupper($captcha) != $cacheCaptcha) {
//            return message("验证码有误", false, []);
//        }
        $password = get_password($password . $examinee_number);
        $checkIsExits = Db::name('member')
            ->where('examinee_number', $examinee_number)
            ->where('password', $password)
            ->where('mark', 1)
            ->field('id,status')
            ->find();
        if (empty($checkIsExits)) {
            return message("账号密码有误", false, []);
        }
        if ($checkIsExits['status'] == 2) {
            return message("账号已禁用,请联系管理员", false, []);
        }
        $JwtObj = new \Jwt();
        $token = $JwtObj->getToken($checkIsExits['id']);
        Db::name('member')
            ->where('id', $checkIsExits['id'])
            ->update(['token_time_out' => time() + 60 * 60 * 24 * 7]);
        return message("操作成功", true, ['token' => $token]);
    }

    /**
     * 获取验证码
     * @return array
     * @since 2023/11/14
     * @author 小码哥
     */
    public function captcha()
    {
        //生成随机UID
        $uuid = get_guid_v4();

        //生成图片验证码
        $verify = new \Verify(['length' => 4, 'useCurve' => true]);
        // 验证码图片
        $img = $verify->entry($uuid);
        // 验证码值
        $code = $verify->getCode();

        // 把内容存入 cache，10分钟后过期
        $key = get_guid_v4();
        Cache::set($key, $code, 10 * 60);
        // 返回结果
        $result = [
            'key' => $key,
            'captcha' => "data:image/png;base64," . base64_encode($img)
        ];
        return message("操作成功", true, $result);
    }

    /**
     * @param $array
     * @param $index
     * @param $value
     * @return array|mixed
     */
    public function filter_by_value($array, $index, $value)
    {
        $newarray = [];
        if (is_array($array) && count($array) > 0) {
            foreach (array_keys($array) as $key) {
                $temp[$key] = $array[$key][$index];
                if ($temp[$key] == $value) {
                    $newarray = $array[$key];
                }
            }
        }
        return $newarray;
    }
}
